package com.xin.filter;

import com.xin.annoations.Permission;
import com.xin.constants.EmployeeConstants;
import com.xin.entity.crm.EmployEntity;
import com.xin.entity.crm.PermissionEntity;
import com.xin.exception.MyException;
import com.xin.service.PermissionService;
import com.xin.service.RoleService;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 校验用户是否有登录，是否具有对应的权限
 */

@Component
public class PermissionFilter implements HandlerInterceptor {
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RoleService roleService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (true) return true;
        //放行登录接口
        if (request.getRequestURL().indexOf("/login")!=-1) return true;
        //校验用户是否携带了token
        String token = request.getHeader("token");
        if (token==null||token.equals("")) throw new MyException("请先登录",401);
        //校验token是否可以取到数据
        EmployEntity employEntity = (EmployEntity)
                redisTemplate.boundHashOps(EmployeeConstants.LOGIN).get(token);
        //获取用户登录的数据
        if (employEntity==null) throw new MyException("登录已过期，请重新登录",401);
        //查询用户所拥有的权限信息
        List<String> employeeHasPermission = this.roleService.findEmployeeHasPermission(employEntity.getId());
        //查看该方法是否需要鉴权
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Permission annotation = method.getAnnotation(Permission.class);
        if (annotation==null) return true;
        String sn = annotation.sn();
        //查看该用户是否拥有该权限
        if (!employeeHasPermission.contains(sn))
            throw new MyException("没有权限访问",403);
            return true;
    }


}
